import type { VNode } from 'vue'
import type { FormInstance } from 'element-plus'
import type { facilityTypeEnum } from '~/store/assetManagement/facilityManagement/typings'
import type { workAreaEnum } from '~/store/assetManagement/assetAreaManage/typings'
import type { PowerDistributionFacilitiesDataItemType } from '../../facilityManagement/powerDistributionFacilities/typings'
import type { AssetHomeMarkerData } from '../map/typings'
import type { PowerDistributionFacilitiesPopoverPropsType } from './typings'
import { ref, reactive } from 'vue'
import { useStore } from 'vuex'
import {
  ElPopover,
  ElCard,
  ElRow,
  ElCol,
  ElDropdown,
  ElDropdownMenu,
  ElDropdownItem,
  ElForm,
  ElFormItem,
  ElDescriptions,
  ElDescriptionsItem,
  ElLink,
  ElButton,
  ElSwitch,
  ElInput,
  ElSelect,
  ElOption,
  ElMessage,
  ElIcon,
  ElSpace,
  ElImage,
  ElTooltip
} from 'element-plus'
import { CaretBottom } from '@element-plus/icons-vue'
import AliIcon from '~/components/AliIocn'
import useVuexGetters from '~/hooks/useVuexGetters'
import { handleTrim } from '~/utils/util'
import styles from '../../index.module.scss'

export default function PowerDistributionFacilitiesPopover(
  props: PowerDistributionFacilitiesPopoverPropsType
): VNode {
  const store = useStore()
  const isEditRef = ref<boolean>()
  const loadingRef = ref<boolean>()
  const disabledDeliverRef = ref<boolean>()
  const ruleFormRef = ref<FormInstance>()
  const formValues = reactive<PowerDistributionFacilitiesDataItemType>({})
  const powerDistributionFacilitiesState = useVuexGetters('powerDistributionFacilities', [
    'facilityTypeSelectList',
    'operationStatusEnum'
  ])
  const assetWorkAreaState = useVuexGetters('assetWorkArea', ['workAreaSelectList'])
  const streetManagementState = useVuexGetters('streetManagement', ['streetSelectList'])

  // 切换工区回调
  const handleChangeWorkArea = (workAreaId: string) => {
    formValues.streetId = undefined
    handleGetStreetSelectList(workAreaId)
  }

  // 获取所属街道下拉列表
  const handleGetStreetSelectList = (workAreaId: string) => {
    store.dispatch('streetManagement/GetStreetSelectListByUser', { workAreaId })
  }

  // 修改是否编辑状态
  const handleChangeIsEditStatus = async () => {
    if (!isEditRef.value) {
      loadingRef.value = true
      const result = await store.dispatch(
        'powerDistributionFacilities/GetPowerDistributionFacilitiesInfo',
        { id: props?.popoverInfo?.assetId }
      )
      if (result?.data) {
        Object.assign(formValues, result?.data, {
          isDeliver: !!result?.data?.isDeliver
        })
        // 如果工区id存在则顺带查询所属街道下拉列表
        if (result?.data?.workAreaId) handleGetStreetSelectList(result?.data?.workAreaId)
        // 设置编辑时投运状态是否禁用
        disabledDeliverRef.value = !!result?.data?.isDeliver
        isEditRef.value = !isEditRef.value
      }
      loadingRef.value = false
      return
    }
    isEditRef.value = !isEditRef.value
  }

  // 提交修改
  const handleSubmitUpdatePowerDistributionFacilitiesInfo = () => {
    ruleFormRef.value!.validate(async (valid: boolean) => {
      if (!valid) return
      loadingRef.value = true
      const params = { ...formValues }
      params.name = handleTrim(params.name!)
      params.isDeliver = params.isDeliver ? 1 : 0
      const res = await store.dispatch(
        'powerDistributionFacilities/UpdatePowerDistributionFacilitiesInfo',
        params
      )
      if (res?.code === 200) {
        ElMessage({ type: 'success', message: '操作成功' })
        props.onCancel!()
        // handleChangeIsEditStatus()
      }
      loadingRef.value = false
    })
  }

  // 切换重合点信息弹框
  const handleChangePointInfo = (record: AssetHomeMarkerData) => {
    props.changeActivePatternMarker(record)
  }

  return (
    <ElPopover
      visible
      placement="bottom"
      teleported={false}
      popperClass={styles['asset-home-info-popover']}
      {...{
        // virtualRef: props.dom,
        virtualRef: {
          getBoundingClientRect() {
            return DOMRect.fromRect({
              width: 0,
              height: 0,
              x: props.left,
              y: props.top
            })
          }
        },
        virtualTriggering: true
      }}
    >
      <ElCard
        class={styles['asset-home-facility-info-card']}
        shadow="never"
        v-slots={{
          header: () => (
            <ElRow>
              <ElCol span={20}>
                {isEditRef.value && '修改'}
                {!isEditRef.value && !props?.pointList?.length && props?.popoverInfo?.name}
                {!isEditRef.value && !!props?.pointList?.length && (
                  <ElDropdown
                    trigger="click"
                    onCommand={handleChangePointInfo}
                    v-slots={{
                      dropdown: () => (
                        <ElDropdownMenu>
                          {props?.pointList?.map((item) => (
                            <ElDropdownItem command={item}>{item.name}</ElDropdownItem>
                          ))}
                        </ElDropdownMenu>
                      )
                    }}
                  >
                    <section>
                      <ElTooltip content={props?.popoverInfo?.name}>
                        {props?.popoverInfo?.name}
                      </ElTooltip>
                      <ElIcon>
                        <CaretBottom />
                      </ElIcon>
                    </section>
                  </ElDropdown>
                )}
              </ElCol>
              <ElCol span={4} {...{ align: 'right' }}>
                {!isEditRef.value && (
                  <>
                    <ElLink
                      type="primary"
                      icon={<AliIcon type="icon-bianji" />}
                      // loading={loadingRef.value}
                      onClick={handleChangeIsEditStatus}
                    />
                    &emsp;
                  </>
                )}
                <ElLink
                  class={styles['asset-home-info-popover-close']}
                  underline={false}
                  onClick={props.onCancel}
                >
                  <AliIcon type="icon-danchuang-guanbi" />
                </ElLink>
              </ElCol>
            </ElRow>
          )
        }}
      >
        {isEditRef.value ? (
          <ElForm ref={ruleFormRef} model={formValues} labelPosition="right">
            <ElFormItem
              prop="isDeliver"
              label="投运状态"
              rules={[{ required: false, message: '请输入投运状态' }]}
            >
              <ElSwitch v-model={formValues.isDeliver} disabled={disabledDeliverRef.value} />
            </ElFormItem>
            <ElFormItem
              prop="name"
              label="设施名称"
              rules={[
                { required: false, whitespace: true, message: '请输入设施名称' },
                { min: 3, whitespace: true, message: '设施名称长度为3～20字符' }
              ]}
            >
              <ElInput v-model={formValues.name} {...{ minlength: 3, maxlength: 20 }} />
            </ElFormItem>
            <ElFormItem
              prop="categoryId"
              label="设施类型"
              rules={[{ required: false, message: '请选择设施类型' }]}
            >
              <ElSelect v-model={formValues.categoryId}>
                {powerDistributionFacilitiesState.facilityTypeSelectList?.value?.map(
                  (item: facilityTypeEnum) => (
                    <ElOption key={item?.id} label={item?.title} value={item?.id!} />
                  )
                ) || []}
              </ElSelect>
            </ElFormItem>
            <ElFormItem
              prop="workAreaId"
              label="所属区域"
              rules={[{ required: false, message: '请选择所属区域' }]}
            >
              <ElSelect v-model={formValues.workAreaId} onChange={handleChangeWorkArea}>
                {assetWorkAreaState.workAreaSelectList?.value?.map((item: workAreaEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                )) || []}
              </ElSelect>
            </ElFormItem>
            <ElFormItem
              prop="streetId"
              label="所属街道"
              rules={[{ required: false, message: '请选择所属街道' }]}
            >
              <ElSelect v-model={formValues.streetId}>
                {streetManagementState.streetSelectList?.value?.map((item: workAreaEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                )) || []}
              </ElSelect>
            </ElFormItem>
            <div {...({ align: 'right' } as any)}>
              <ElButton onClick={handleChangeIsEditStatus}>取消</ElButton>
              <ElButton
                type="primary"
                onClick={handleSubmitUpdatePowerDistributionFacilitiesInfo}
                loading={loadingRef.value}
              >
                保存
              </ElButton>
            </div>
          </ElForm>
        ) : (
          <ElDescriptions column={1}>
            {props?.popoverInfo?.infoList?.map((item) => (
              <ElDescriptionsItem label={item.key}>
                {item.type === 'text' && item.value}
                {item.type === 'image' && item.value && typeof item.value === 'string' && (
                  <ElSpace>
                    {item.value?.split(',')?.map((url: string, index: number, arr: string[]) => (
                      <ElImage
                        class={styles['asset-home-light-info-image']}
                        src={url}
                        previewSrcList={arr}
                        initialIndex={index}
                        previewTeleported
                      />
                    ))}
                  </ElSpace>
                )}
              </ElDescriptionsItem>
            ))}
          </ElDescriptions>
        )}
      </ElCard>
    </ElPopover>
  )
}
